<?php

class Util
{
    public static function GetDatabaseTableName($tableName)
    {
        global $wpdb;
        return $wpdb->prefix . PLUGIN_DB_PREFIX . $tableName;
    }


    public static function QuoteArray( $array )
    {
        foreach ( $array as &$value )
        {
            $value = self::Quote( $value );
        }
        return $array;
    }

    public static function QuoteParams( QueryParams $params )
    {
        self::QuoteArray( $params->GetArray() );
    }

    public static function Quote( $value )
    {
        return Core::DBConn()->Quote($value);
    }

    public static function QuoteForLikeExpression( $value )
    {
        return Core::DBConn()->QuoteForLikeExpression( $value );
    }

    public static function QuoteString( $string )
    {
        return "'" . Util::Quote($string) . "'";
    }

    public static function QuoteStringArray( $array )
    {
        foreach ( $array as &$value )
        {
            $value = self::QuoteString( $value );
        }

        return $array;
    }

    public static function GetWhereParam( $array, $operator = 'AND' )
    {
        $result = '';
        foreach ( $array as $item )
        {
            if ( !empty($result) )
            {
                $result .= " {$operator} ";
            }

            if ( is_array($item) )
            {
                $result .= '(' . self::GetWhereParam($item, 'OR') . ')';
            }
            else
            {
                $result .= $item;
            }
        }

        return $result;
    }

    public static function GetHtmlEntities( $value )
    {
        $value = htmlentities( iconv( 'UTF-8', 'UTF-8//IGNORE', $value), ENT_QUOTES, 'UTF-8');
        return $value;
    }

    public static function GetBooleanAsString( $bool )
    {
        return self::GetAsBoolean($bool) ? "true" : "false";
    }

    public static function GetAsBoolean( $bool )
    {
        return (bool)($bool && $bool !== 'false');
    }

    public static function GetFilename( $path )
    {
        $info = pathinfo($path);
        return $info['basename'];
    }

    public static function SetIfEmpty( &$var, $value )
    {
        if ( empty($var) )
        {
            $var = $value;
        }
    }

    public static function SetIfNull( &$var, $value )
    {
        if ( is_null($var) )
        {
            $var = $value;
        }
    }

    public static function SetIfEmptyString( &$var, $value )
    {
        if ( $var === '' )
        {
            $var = $value;
        }
    }

    public static function SetIfNullOrEmptyString( &$var, $value )
    {
        if ( is_null($var) || $var === '' )
        {
            $var = $value;
        }
    }

    public static function SetIfNullOrEmptyArray( &$var, $value )
    {
        if ( is_null( $var ) || count( $var ) == 0 )
        {
            $var = $value;
        }
    }

    /**
     * Redirects to specified URL.
     *
     * @param string $url URL to redirect to
     * @param int $statusCode HTTP status code for redirection.
     *      302 Found by default
     */
    public static function Redirect($url, $statusCode = null)
    {
        if (isset($statusCode))
        {
            header("Location: $url", true, $statusCode);
        }
        else
        {
            header("Location: $url");
        }
        exit();
    }

    public static function GetParametrizedString( $string, $vars )
    {
        $varPatterns = array();
        $values = array();
        foreach ($vars as $name => $value)
        {
            array_push($varPatterns, "%$name%");
            array_push($values, $value);
        }
        return str_replace($varPatterns, $values, $string);
    }

    public static function SetStatusCode( $code, $text = null )
    {
        if ( empty($code) )
        {
            return;
        }

        header("Status: $code $text", true);
        header("HTTP/1.0 $code $text", true);
    }

    /**
     * @param string $dir - path
     * @param string $name - new folder name
     * @return bool (if folder was created returns true)
     */
    public static function CreateFolder($dir, $name)
    {
        if (is_dir($dir) && !file_exists($dir. $name))
        {
            @mkdir($dir . $name);
            return true;
        }

        return false;
    }

    /**
     *
     * Creates folder recursively
     * @param string $dir
     * @param int $mask (For *nix systems)
     */
    public static function CreateFolderRecursively( $dir, $mask = 0777 )
    {
        if ( file_exists( $dir ) )
        {
            return;
        }

        $parent = dirname( $dir );
        self::CreateFolderRecursively( $parent, $mask );

        mkdir( $dir, $mask );
    }

    /**
     * Get all entries(files and folders) from dir without recursion
     * @param string $dir - directory path
     * @param array $excludes
     * @return array - files from dir
     */
    public static function GetDirEntries($dir, $excludes = null)
    {
        $entries = array();
        if (is_dir($dir))
        {
            if (($res = opendir($dir)) !== false)
            {
                while (($entry = readdir($res)) !== false)
                {
                    if ( $entry != '..' && $entry != '.' && !self::MatchFileName($excludes, $entry) )
                    {
                        $entries[] = $entry;
                    }
                }
                closedir($res);
            }
        }
        return $entries;
    }

    public static function MatchFileName( $patterns, $filename )
    {
        $patterns = (array)$patterns;
        $useFnMatch = function_exists('fnmatch');
        foreach ($patterns as $pattern)
        {
            if (!$useFnMatch)
            {
                if ( (@preg_match('/^' . strtr(addcslashes($pattern, '/\\.+^$(){}=!<>|'),
                    array('*' => '.*', '?' => '.?')) . '$/i', $filename) ) )
                {
                    return true;
                }
            }
            else if ( fnmatch($pattern, $filename) )
            {
                return true;
            }
        }

        return false;
    }

    /**
     * Returns path relative to $compareTo, expands all '..' components.
     *
     * @param string $path Relative path
     * @param string $root Absolute or relative path
     * @return string
     */
    public static function GetPathFromRoot($path, $root)
    {
        $path = str_replace('\\', '/', $path);
        $path = trim($path, '/');
        $root = str_replace('\\', '/', $root);
        $root = rtrim($root, '/');

        // $path cannot be absolute
        if ( preg_match('/^[A-Za-z]:/', $path) )
        {
            return false;
        }

        return preg_replace('/\w+\/\.\.\//', '', $root . '/' . $path);
    }

    public static function GetArrayCorrectString($array, $value, $defaultValue = "")
    {
        return isset($array[$value]) ? $array[$value] : $defaultValue;
    }

    public static function GetCorrectString($value, $defaultValue)
    {
        return Util::GetArrayCorrectString($_GET, $value, $defaultValue);
    }

    public static function ToArrayValue( $value )
    {
        $value = trim($value);
        return !empty($value) ? array_map('trim', explode(',', $value)) : array();
    }

}

function __HandleXmlError( $errno, $errstr, $errfile, $errline )
{
    if ( strpos($errstr,"DOMDocument::loadXML()") === false )
    {
        return false;
    }
    throw new DOMException($errstr);
}

?>
